package com.yangcangclub.mq.domain;

import com.yangcangclub.mq.bean.MQMessageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangcangclub.commons.exception.ApolloException;
import com.yangcangclub.commons.result.MessageEnum;
import com.yangcangclub.mq.base.MQBaseDomain;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author flyger
 * @date 2016-07-21
 * @desc MQTopic domain
 */
@Component
public class MQMessageProfile extends MQBaseDomain {

    /**
     * 添加
     * @param partition
     * @param topic
     * @return
     */
    public  int addMQTopicMessage(int partition,String topic, String key, String tag, String content){

        MQMessageInfo mqMessageInfo = new MQMessageInfo();
        mqMessageInfo.setPartition_(partition);
        mqMessageInfo.setTopic(topic);
        mqMessageInfo.setKey_(key);
        mqMessageInfo.setTag(tag);
        mqMessageInfo.setContent(content);

        super.getMasterJdbc().insert("mq.MQMapper.insertMQTopicMessage",mqMessageInfo);

        if(mqMessageInfo.getId() == 0) {
            throw new ApolloException(MessageEnum.PLEASE_REPLY);
        }

        return mqMessageInfo.getId();
    }

    /**
     * 获取服务器所有未消费的消息
     * @return
     */
    public List<MQMessageInfo> getServerMQTopicMessageList(String topic,int partition){

        Map<String,Object> map = Maps.newHashMap();
        map.put("topic",topic);
        map.put("partition_",partition);

        List<MQMessageInfo> mqMessageInfoList = super.getSlaveJdbc().selectList("mq.MQMapper.selectServerMQTopicMessageList",map);

        if(null==mqMessageInfoList) {
            return Lists.newArrayList();
        }

        return mqMessageInfoList;
    }

    /**
     * 按tag获取服务器所有未消费的消息
     * @return
     */
    public List<MQMessageInfo> getServerMQTopicMessageList(String topic,int partition,String tag,int offset){

        Map<String,Object> map = Maps.newHashMap();
        map.put("topic",topic);
        map.put("partition_",partition);
        map.put("tag",tag);
        map.put("offset",offset);

        List<MQMessageInfo> mqMessageInfoList = super.getSlaveJdbc().selectList("mq.MQMapper.selectServerMQTopicMessageListByTag",map);

        if(null==mqMessageInfoList) {
            return Lists.newArrayList();
        }

        return mqMessageInfoList;
    }

    /**
     * 更新消息已消费
     * @param id
     * @return
     */
    public boolean updateMqTopicMessageIsConsume(int id) {

        Map<String,Object> map = Maps.newHashMap();
        map.put("id", id);

        int i =  super.getMasterJdbc().update("mq.MQMapper.updateMqTopicMessageIsConsume", map);

        if(i != 1) {
            //回滚
            throw new ApolloException(MessageEnum.DATABASE_ERROR);
        }

        return true;
    }
}
